import 'package:edu/constants/app_strings.dart';
import 'package:edu/networks/business/models/business_response.dart';
import 'package:edu/pages/common/course_list_cell_widget.dart';
import 'package:edu/pages/common/dot_radio_button_widget.dart';
import 'package:edu/pages/common/empty_content_widget.dart';
import 'package:edu/pages/supplement/%20shopping_cart/shopping_cart_page_logic.dart';
import 'package:edu/utils/app_router.dart';
import 'package:edu/utils/app_theme.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:tuple/tuple.dart';

class ShoppingCartPage extends StatefulWidget {
  const ShoppingCartPage({super.key});

  @override
  State<ShoppingCartPage> createState() => _ShoppingCartPageState();

  // 在其他地方已购买
  static final purchasedCourseIdNotifier = ValueNotifier<Tuple2<int, double>>(
    const Tuple2(0, 0.0),
  );
}

class _ShoppingCartPageState extends State<ShoppingCartPage> {
  @override
  void initState() {
    super.initState();
    context.read<ShoppingCartPageLogic>().init();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(context),
      body: _buildMainBody(context),
      bottomNavigationBar: _buildBottomNavigationBar(context),
    );
  }

  AppBar _buildAppBar(BuildContext context) {
    final fontSize = Theme.of(context).textTheme.titleMedium?.fontSize ?? 16;
    return AppBar(
      centerTitle: true,
      title: Text(
        AppStrings.shoppingCart,
        style: TextStyle(fontSize: fontSize, fontWeight: FontWeight.bold),
      ),
      actions: [
        TextButton(
          onPressed: () {
            context.read<ShoppingCartPageLogic>().toggleEditing();
          },
          child: Selector<ShoppingCartPageLogic, bool>(
            selector: (_, logic) => logic.editing,
            builder: (context, value, child) {
              final title = value ? AppStrings.cancel : AppStrings.edit;
              return Text(
                title,
                style: Theme.of(context).textTheme.titleMedium,
              );
            },
          ),
        ),
        const SizedBox(width: 16),
      ],
    );
  }

  Widget _buildMainBody(BuildContext context) {
    return Selector<ShoppingCartPageLogic, bool>(
      selector: (_, logic) => logic.isContentEmpty,
      builder: (context, v, child) {
        if (v) {
          return Selector<ShoppingCartPageLogic, Tuple2<bool, bool>>(
            selector: (_, logic) => Tuple2(logic.loading, logic.error),
            builder: (context, item, child) {
              return EmptyContentWidget(
                isLoading: item.item1,
                isError: item.item2,
                reloadAction: () {
                  context.read<ShoppingCartPageLogic>().loadOrders();
                },
              );
            },
          );
        } else {
          return _buildCartList(context);
        }
      },
    );
  }

  // 购物车列表
  Widget _buildCartList(BuildContext context) {
    return Selector<ShoppingCartPageLogic, Tuple2<int, bool>>(
      selector: (_, logic) => Tuple2(logic.orders.length, logic.canLoadMore),
      builder: (context, v, child) {
        final logic = context.read<ShoppingCartPageLogic>();
        final orders = logic.orders;
        final canLoadMore = v.item2;
        final itemCount = canLoadMore ? v.item1 + 1 : v.item1;
        return ListView.builder(
          itemCount: itemCount,
          itemBuilder: (context, index) {
            final order = index < v.item1 ? orders[index] : null;
            if (order != null) {
              return _ShoppingCartItemWidget(
                order: order,
                onTap: () {
                  context.pushNamed(
                    AppRouter.kCourseDetail,
                    queryParameters: {'id': order.id.toString()},
                  );
                },
              );
            }
            return Center(
              child: Padding(
                padding: const EdgeInsets.all(10.0),
                child: Builder(
                  builder: (context) {
                    Future.delayed(Duration.zero, () {
                      logic.loadOrders();
                    });
                    return const CircularProgressIndicator();
                  },
                ),
              ),
            );
          },
        );
      },
    );
  }

  // 底部导航栏
  Widget _buildBottomNavigationBar(BuildContext context) {
    return Selector<ShoppingCartPageLogic, bool>(
      selector: (context, logic) => logic.isContentEmpty,
      builder: (context, v, child) {
        if (v) {
          return const SizedBox.shrink();
        } else {
          final priceStyle = Theme.of(
            context,
          ).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.bold);
          final purchaseTextColor = AppTheme.shared.whiteColor;
          final purchaseTextStyle = Theme.of(context).textTheme.titleSmall
              ?.copyWith(color: purchaseTextColor, fontWeight: FontWeight.bold);
          return BottomAppBar(
            height: 60,
            padding: EdgeInsets.zero,
            child: Row(
              children: [
                const SizedBox(width: 16),
                // 全选
                Selector<ShoppingCartPageLogic, bool>(
                  selector: (_, logic) => logic.isAllSelected,
                  builder: (context, sel, child) {
                    return DotRadioButtonWidget(
                      radius: 10,
                      strokeColor: AppTheme.shared.greyColor,
                      strokeWidth: 2,
                      dotColor: Theme.of(context).colorScheme.primary,
                      value: sel,
                      onChanged: (enable) {
                        context.read<ShoppingCartPageLogic>().selectAll(enable);
                      },
                    );
                  },
                ),
                const SizedBox(width: 8),
                Text(
                  AppStrings.selectAll,
                  style: Theme.of(context).textTheme.titleMedium,
                ),
                const SizedBox(width: 16),
                // 总价
                Selector<ShoppingCartPageLogic, bool>(
                  selector: (context, logic) => logic.editing,
                  builder: (context, v, child) {
                    if (!v) {
                      return Text(
                        '${AppStrings.totalPrice}:',
                        style: priceStyle,
                      );
                    } else {
                      return const SizedBox.shrink();
                    }
                  },
                ),
                // 总价数值
                Selector<ShoppingCartPageLogic, Tuple2<bool, double>>(
                  selector: (context, logic) {
                    final v1 = logic.editing;
                    final v2 = (logic.totalPrice ?? 0.0).clamp(
                      0.0,
                      double.infinity,
                    );
                    return Tuple2(v1, v2);
                  },
                  builder: (context, v, child) {
                    if (v.item1) {
                      return const SizedBox.shrink();
                    } else {
                      return Text(
                        v.item2.toStringAsFixed(2),
                        style: priceStyle,
                      );
                    }
                  },
                ),
                const Spacer(),
                // 结算 or 删除
                SizedBox(
                  width: 90,
                  child: TextButton(
                    onPressed: () async {
                      final logic = context.read<ShoppingCartPageLogic>();
                      final title = logic.editing
                          ? AppStrings.confirmDelete
                          : AppStrings.confrimPurchase;
                      final confrim = await showDialog<bool>(
                        context: context,
                        builder: (context) => AlertDialog(
                          title: Text(title),
                          actions: [
                            TextButton(
                              onPressed: () => Navigator.of(context).pop(false),
                              child: const Text(AppStrings.cancel),
                            ),
                            TextButton(
                              onPressed: () => Navigator.of(context).pop(true),
                              child: const Text(AppStrings.confirm),
                            ),
                          ],
                        ),
                      );
                      if (confrim == true) {
                        if (logic.editing) {
                          logic.delete();
                        } else {
                          /*购买结算, 待开发*/
                          logic.purchase();
                        }
                      }
                    },
                    style: TextButton.styleFrom(
                      backgroundColor: AppTheme.shared.purchaseTipColor,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(30),
                      ),
                      padding: const EdgeInsets.symmetric(vertical: 7),
                    ),
                    child: Selector<ShoppingCartPageLogic, bool>(
                      selector: (_, logic) => logic.editing,
                      builder: (context, value, child) {
                        final title = value
                            ? AppStrings.delete
                            : AppStrings.goToPay;
                        return Text(title, style: purchaseTextStyle);
                      },
                    ),
                  ),
                ),
                const SizedBox(width: 16),
              ],
            ),
          );
        }
      },
    );
  }
}

class _ShoppingCartItemWidget extends StatelessWidget {
  final CourseOrder order;
  final GestureTapCallback? onTap;

  const _ShoppingCartItemWidget({required this.order, this.onTap});

  @override
  Widget build(BuildContext context) {
    final logic = context.read<ShoppingCartPageLogic>();
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        const SizedBox(width: 16),
        Selector<ShoppingCartPageLogic, bool>(
          selector: (_, logic) => logic.selectedOrderIds.contains(order.id),
          builder: (context, v, child) {
            return DotRadioButtonWidget(
              radius: 10,
              strokeColor: AppTheme.shared.greyColor,
              strokeWidth: 2,
              dotColor: Theme.of(context).colorScheme.primary,
              value: v,
              onChanged: (enable) {
                logic.courseItemSelectionChanged(order.id, enable, order.price);
              },
            );
          },
        ),
        Expanded(
          child: GestureDetector(
            onTap: onTap,
            child: CourseListCellWidget(course: order),
          ),
        ),
      ],
    );
  }
}
